package com.example.itemdecoration.service;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by TAOTAO.
 * Date: 2020/7/11
 * Time: 11:15
 */
public class MyService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAOTAO", "MyService 已启动！");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("TAOTAO", "onBind 已启动！");
        return messenger.getBinder();
    }

    class MessHander extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            Log.d("TAOTAO", "MessHander:" + msg.what);
            Messenger message = msg.replyTo;
            Message message1 = Message.obtain(null, 2, 0, 0);
            Bundle bundle = new Bundle();
            bundle.putString("key", "接收Service返回的值");
            message1.setData(bundle);
            try {
                message.send(message1);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            super.handleMessage(msg);
        }
    }

    private Messenger messenger = new Messenger(new MessHander());

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAOTAO", "onStartCommand 已启动！");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("TAOTAO", "onUnbind 已启动！");

        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        Log.d("TAOTAO", "onDestroy 已启动！");
        super.onDestroy();
    }
}
